<template>
  <el-upload
      :limit="limit"
      v-model:file-list="fileList"
      action="/api/system/common/upload"
      list-type="picture-card"
      :on-success="handleAvatarSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :headers="headers"
  >
    <el-icon><Plus /></el-icon>

  </el-upload>
  <span style="margin-left: 5px;color: red">最多可上传{{limit}}张</span>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, ref, watchEffect} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {ElMessage, type UploadProps, type UploadUserFile} from 'element-plus'
import {useUserStore} from "@/stores/user.ts";

const imgList = ref([])
const props = defineProps(['images','t','limit'])
const limit=ref()
const imageList = ref([])
let fileList;
watchEffect(()=>{
  const t = props.t
  console.log("t",t)
  limit.value = props.limit
  imageList.value = props.images
  imgList.value=props.images;
  fileList=ref<UploadUserFile[]>(imageList.value)
})

const userStore = useUserStore();
const token = userStore.token
const headers = ref({
  'Authorization':token
})




const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  imgList.value.forEach((item, index) => {
    if (item.name == uploadFile.name){
      imgList.value.splice(index, 1)
      emit('imgData', imgList.value)
    }
  })
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const emit = defineEmits(['imgData'])
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  // const imageUrl = URL.createObjectURL(uploadFile.raw!)
  console.log("上传成功"+response.data.substring(response.data.lastIndexOf('/') + 1))
  imgList.value.push({"name": response.data.substring(response.data.lastIndexOf('/') + 1),"url":response.data})
  emit('imgData', imgList.value)
  console.log("文件列表:",fileList.value)
}
</script>
